package sing.cloud.alibaba.seata.service.impl;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sing.cloud.alibaba.seata.mapper.IOrderMapper;
import sing.cloud.alibaba.seata.service.IOrderService;
import sing.cloud.alibaba.seata.domain.Order;
import sing.cloud.alibaba.seata.service.feign.IAccountFeignService;
import sing.cloud.alibaba.seata.service.feign.IStorageFeignService;

/**
 * @author xing
 * @date 2022/9/3 17:44
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

//    @Autowired
//    private IOrderMapper orderMapper;
//    @Autowired
//    private IStorageFeignService storageService;
//    @Autowired
//    private IAccountFeignService accountService;

    private final IOrderMapper orderMapper;
    private final IStorageFeignService storageService;
    private final IAccountFeignService accountService;

    public OrderServiceImpl(IOrderMapper orderMapper, IStorageFeignService storageService, IAccountFeignService accountService) {
        this.orderMapper = orderMapper;
        this.storageService = storageService;
        this.accountService = accountService;
    }

    @Override
    @GlobalTransactional(name = "my_test_tx_group", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("xid in create method: {}", RootContext.getXID());
        log.info("------->下单开始");
        //本应用创建订单
        int i = orderMapper.create(order);
//        if(i != 0) {
//            log.info("create order success, order userID: {}", order.getUserId());
//        } else {
//            log.error("create order failed, order userId: {}", order.getUserId());
//        }

        //远程调用库存服务扣减库存
        log.info("------->order-service中扣减库存开始");
        storageService.decrease(order.getProductId(),order.getCount());
        log.info("------->order-service中扣减库存结束");

        //远程调用账户服务扣减余额
        log.info("------->order-service中扣减余额开始");
        accountService.decrease(order.getUserId(),order.getMoney());
        log.info("------->order-service中扣减余额结束");

        //修改订单状态为已完成
        log.info("------->order-service中修改订单状态开始");
        int update = orderMapper.updateEndOrderForNotEndById(order.getUserId());
//        if(update != 0) {
//            log.info("update order success, userId: {}", order.getUserId());
//        } else {
//            log.info("update order failed, userId: {}", order.getUserId());
//        }
        log.info("------->order-service中修改订单状态结束");

        log.info("------->下单结束");
//        return "end";
    }
}
